package com.farmer.lazycoder.controllers;

import com.farmer.lazycoder.util.DBUtil;
import com.farmer.lazycoder.vo.ConnectionInfo;
import com.lanjor.commons.bean.OutputJson;
import com.lanjor.commons.serializer.Serializer;
import com.lanjor.commons.utils.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * @auther yz
 * @date 2019/3/27
 **/
@Controller
@RequestMapping("/home")
public class HomeController {


    @RequestMapping("/index")
    public String index () throws Exception {
        return "/view/index";
    }

    @RequestMapping("/connectToDb")
    @ResponseBody
    public OutputJson connectToDb(String info,HttpServletRequest request) throws Exception {
        OutputJson opjson = new OutputJson();
        ConnectionInfo connectionInfo = null;
        try {
            connectionInfo = Serializer.deserializeJson(info,ConnectionInfo.class);
        } catch(Exception e) {
            e.printStackTrace();
        }
        if (connectionInfo == null) {
            opjson.setMessage("参数错误");
        } else if (StringUtils.isBlank(connectionInfo.getIp())) {
            opjson.setMessage("请输入IP");
        } else if (StringUtils.isBlank(connectionInfo.getPort())) {
            opjson.setMessage("请输入密码");
        } else if (StringUtils.isBlank(connectionInfo.getDbname())) {
            opjson.setMessage("请输入数据库名称");
        } else if (StringUtils.isBlank(connectionInfo.getUserName())) {
            opjson.setMessage("请输入用户名");
        } else if (StringUtils.isBlank(connectionInfo.getPassword())) {
            opjson.setMessage("请输入密码");
        } else {
            request.getSession().setAttribute("dbinfo",connectionInfo);
            Connection connection = DBUtil.getConnection(connectionInfo);
            if (connection!=null) {
                DatabaseMetaData metaData = connection.getMetaData();
                ResultSet rs = metaData.getTables(connection.getCatalog(), null, null, new String[]{"TABLE"});
                List<String> tables = new ArrayList<>();
                while (rs.next()) {
                    String table = rs.getString("TABLE_NAME");
                    tables.add(table);
                }
                opjson.setObj(tables);
                opjson.setStatus(true);
            }
        }
        return opjson;
    }
}
